#include "custom_data.h"

#include <common/log/log.h>
#include <common/net/session.h>

#include <common.pb.h>
#include <login.pb.h>

#include "base/account_mgr.h"
#include "base/player.h"
#include "base/sub_server_mgr.h"

uint32_t CltSessionCustomData::getPlayerID()
{
    return player_ ? player_->getID() : 0;
}

void CltSessionCustomData::onSessionClose()
{
    const auto& subMgr = ServerMgr::get().getSubServ<SubServerMgr>();
    if (!subMgr)
    {
        LOG_ERROR("no sub manager was found.");
        return;
    }

    if (!player_)
    {
        return;
    }

    uint32_t playerID = getPlayerID();
    auto accMgr = subMgr->getSubMgr<AccountMgr>(SubManagerType::eAccount);
    auto accInfo = accMgr->getAccInfo(playerID);
    if (!accInfo)
    {
        LOG_ERROR("no account was found, playerID: " << playerID);
        return;
    }

    accInfo->curLoginSession.reset();

    const auto& gsSession = player_->getGsSession();
    if (!gsSession)
    {
        return;
    }

    proto::login::ClientCloseReq msg;
    std::string buf = msg.SerializeAsString();

    proto::common::CommonGateReq req;
    req.set_player_id(playerID);
    req.set_msg_id(proto::login::C2S_CLIENT_CLOSE_REQ);
    req.set_msg_len(buf.size());
    req.set_msg(std::move(buf));

    gsSession->sendMsg(proto::common::eCommon, proto::common::C2S_COMMON_GATE_REQ, req);
}

// void GsSessionCustomData::onSessionClose()
// {

// }

// void GsSessionCustomData::addCltSession(uint32_t playerID, const std::shared_ptr<Session>& session)
// {
//     if (!session)
//     {
//         LOG_ERROR("sessin is null.");
//         return;
//     }
//     std::lock_guard<std::mutex> lock(mutex_);
//     cltSessions_[playerID] = session;
// }

// std::shared_ptr<Session> GsSessionCustomData::getCltSession(uint32_t playerID)
// {
//     std::lock_guard<std::mutex> lock(mutex_);
//     const auto& it = cltSessions_.find(playerID);
//     return it == cltSessions_.end() ? std::shared_ptr<Session>() : it->second.lock();
// }

// void GsSessionCustomData::removeCltSession(uint32_t playerID)
// {
//     std::lock_guard<std::mutex> lock(mutex_);
//     cltSessions_.erase(playerID);
// }
